/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.dona.imsidetector.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.viewbinding.ViewBinding;

import com.dona.imsidetector.DemoDataProvider;
import com.dona.imsidetector.R;
import com.dona.imsidetector.core.BaseFragment;
import com.dona.imsidetector.databinding.FragmentLinkageRecyclerviewBinding;
import com.dona.imsidetector.db.entity.ListItem;
import com.dona.imsidetector.fragment.linkage.custom.CustomGroupedItem;
import com.dona.imsidetector.fragment.linkage.custom.CustomLinkagePrimaryAdapterConfig;
import com.dona.imsidetector.fragment.linkage.custom.CustomLinkageSecondaryAdapterConfig;
import com.dona.imsidetector.utils.DataProvider;
import com.dona.imsidetector.utils.DeviceUtil;
import com.dona.imsidetector.utils.IMSIUtil;
import com.dona.imsidetector.utils.MMKVUtils;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.kunminx.linkage.LinkageRecyclerView;
import com.kunminx.linkage.adapter.viewholder.LinkagePrimaryViewHolder;
import com.kunminx.linkage.adapter.viewholder.LinkageSecondaryViewHolder;
import com.kunminx.linkage.bean.BaseGroupedItem;
import com.kunminx.linkage.bean.DefaultGroupedItem;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.utils.SnackbarUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.button.ButtonView;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xutil.common.StringUtils;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.stream.Collectors;

import butterknife.BindView;

import static androidx.constraintlayout.widget.Constraints.TAG;

/**
 * @author xuexiang
 * @since 2019-11-25 16:52
 */
@Page(name = "设置频点")
public class FreqSelectorFragment extends BaseFragment<FragmentLinkageRecyclerviewBinding> implements CustomLinkagePrimaryAdapterConfig.OnPrimaryItemClickListener, CustomLinkageSecondaryAdapterConfig.OnSecondaryItemClickListener {


    public static final String FKEY = "freqs";
    private MaterialDialog addFreqDialog;

    /**
     * 布局的资源id
     *
     * @return
//     */
//    @Override
//    protected int getLayoutId() {
//        return R.layout.fragment_linkage_recyclerview;
//    }

    @NonNull
    @NotNull
    @Override
    protected FragmentLinkageRecyclerviewBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentLinkageRecyclerviewBinding.inflate(inflater,container,false);
    }

    @SuppressLint("ResourceType")
    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
//        titleBar.addAction(new TitleBar.TextAction("切换") {
//            @SingleClick
//            @Override
//            public void performAction(View view) {
//                view.getLayoutParams().width = 100;
//                if (binding.linkage != null) {
//                    binding.linkage.setGridMode(!binding.linkage.isGridMode());
//                }
//            }
//        });
//        com.xuexiang.xpage.utils.TitleBar.inflate(this.getContext(),R.menu.menu_custom,titleBar);

        TitleBar.TextAction textAction1 = new TitleBar.TextAction("添加") {
            @Override
            public void performAction(View view) {
                addFreqDialog = new MaterialDialog.Builder(getContext())
                        .autoDismiss(false)
                        .customView(R.layout.dialog_add_freq, true)
                        .title("添加")
                        .positiveText("确定")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                View rvv = dialog.getView();
                                EditText freqEdit = (EditText) rvv.findViewById(R.id.et_freq);
                                Spinner ispSpinner =  rvv.findViewById(R.id.spinner_isp);
                                String freq = freqEdit.getText().toString();
                                String isp = ispSpinner.getSelectedItem().toString();
                                Log.e(TAG, "onClick: " + isp );
                                if(freq.contains(",") || freq.contains("，")){
                                    freq = freq.replaceAll("，",",");
                                    String[] freqs = freq.split(",");

                                    for (String feq:freqs){
                                        boolean f = true;
                                        for(int i=0;i<defaultItems.size();i++){
                                            if(defaultItems.get(i).info!=null
                                                    && defaultItems.get(i).info.getContent().equals(feq)
                                                    && defaultItems.get(i).info.getGroup().equals(isp)){
                                                f = false;
                                                SnackbarUtils.Short(view, feq + "重复").show();
                                                break;
                                            }
                                        }
                                        if(f) {
                                            defaultItems.add(new CustomGroupedItem(new CustomGroupedItem.ItemInfo(feq, isp, feq, 0)));
                                        }
                                    }
                                }else{
                                    boolean f = true;
                                    sortList();
                                    for(int i=0;i<defaultItems.size();i++){
                                        if(defaultItems.get(i).info!=null
                                                && defaultItems.get(i).info.getContent().equals(freq)
                                                && defaultItems.get(i).info.getGroup().equals(isp)){
                                            f = false;
                                            SnackbarUtils.Short(view, isp + freq + "重复").show();
                                            break;
                                        }
                                    }
                                    if(f) {
                                        defaultItems.add(new CustomGroupedItem(new CustomGroupedItem.ItemInfo(freq, isp, freq, 0)));
                                    }

                                }
                                dialog.dismiss();
                                String jsonStr = new Gson().toJson(defaultItems).replaceAll("\\{\"info\":\\{\"group\":\"GSM\"\\},\"isHeader\":false\\},","");
                                MMKVUtils.put(FKEY,jsonStr);
//                                defaultItems = MMKVUtils.getObjectList(FKEY,CustomGroupedItem.class);
                                sortList();
//                                Log.e(TAG, "onClick: " + new Gson().toJson(defaultItems));

                                binding.linkage.getSecondaryAdapter().initData(defaultItems);
                                binding.linkage.getSecondaryAdapter().notifyDataSetChanged();
                            }
                        })
                        .negativeText("取消")
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.dismiss();
                            }
                        })
                        .build();



                WindowManager.LayoutParams p = addFreqDialog.getWindow().getAttributes();
                p.width = 1000;
                p.height = 600;
                addFreqDialog.getWindow().setAttributes(p);
                View rvv = addFreqDialog.getView();

                addFreqDialog.show();

            }


        };

        TitleBar.TextAction textAction3 = new TitleBar.TextAction("设置") {
            @Override
            public void performAction(View view) {

            }



        };

        TitleBar.ActionList actionList= new TitleBar.ActionList();
        actionList.add(textAction1);
//        actionList.add(textAction2);
//        actionList.add(textAction3);
        titleBar.addActions(actionList);
        return titleBar;
    }


    void sortList(){
//        Log.e(TAG, "sortList: "+ defaultItems.size() +",,," + new Gson().toJson(defaultItems)  );
        List<CustomGroupedItem> newList = new ArrayList<>();
        newList.addAll(defaultItems);
        for(int i=0;i<newList.size();i++){
//            Log.e(TAG, "sortList: " + new Gson().toJson(newList.get(i) ));
            if(!(newList.get(i) instanceof CustomGroupedItem)){
//                Log.e(TAG, "sortList_del1: " + true  );
                defaultItems.remove(i);
                continue;
            }

            if(newList.get(i).isHeader)continue;

//            try {
//                Log.e(TAG, "sortListry: " + defaultItems.get(i).info.getContent());
//            }catch (Exception e){
//                Log.e(TAG, "sortListerr: " + e.getMessage() );
//            }

            if(newList.get(i).info.getContent()==null){
                defaultItems.remove(i);
                Log.e(TAG, "sortList_del2: " + defaultItems.size()  );
            }
        }

        Collections.sort(defaultItems, new Comparator<CustomGroupedItem>() {


            @Override
            public int compare(CustomGroupedItem o1, CustomGroupedItem o2) {

                Log.e(TAG, "compare: " + new Gson().toJson(o2) +"  **  " + new Gson().toJson(o1));
                if (!o2.isHeader && o1.isHeader) {
                    if (o1.header.equals("TDD-移动")) {
                        return -1;
                    } else if (o1.header.equals("FDD-移动")) {
                        if (o2.info.getGroup().equals("TDD-移动")) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }  else if (o1.header.equals("FDD-联通")) {
                        if (o2.info.getGroup().equals("TDD-移动") || o2.info.getGroup().equals("FDD-移动") ) {
                            return 1;
                        } else {
                            return -1;
                        }
                    } else if (o1.header.equals("FDD-电信")) {
                        if (o2.info.getGroup().equals("TDD-移动") || o2.info.getGroup().equals("FDD-移动")|| o2.info.getGroup().equals("FDD-联通")) {
                            return 1;
                        } else {
                            return -1;
                        }
                    } else if (o1.header.equals("WCDMA")) {
                        if (o2.info.getGroup().equals("TDD-移动")
                                || o2.info.getGroup().equals("FDD-移动")
                                || o2.info.getGroup().equals("FDD-联通")
                                || o2.info.getGroup().equals("FDD-电信")) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }else if (o1.header.equals("GSM")) {
                        if (o2.info.getGroup().equals("TDD-移动")
                                || o2.info.getGroup().equals("FDD-移动")
                                || o2.info.getGroup().equals("FDD-联通")
                                || o2.info.getGroup().equals("FDD-电信")
                                || o2.info.getGroup().equals("WCDMA")) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }
                }else if(!o2.isHeader && !o1.isHeader){
                    if(o1.info.getGroup().equals(o2.info.getGroup())){
                        return Integer.valueOf(o1.info.getContent()).compareTo(Integer.valueOf(o2.info.getContent()));
                    }else if (o1.info.getGroup().equals("TDD-移动")) {
                        return -1;
                    } else if (o1.info.getGroup().equals("FDD-移动")) {
                        if (o2.info.getGroup().equals("TDD-移动") ) {
                            return 1;
                        } else {
                            return -1;
                        }
                    } else if (o1.info.getGroup().equals("FDD-联通")) {
                        if (o2.info.getGroup().equals("TDD-移动") || o2.info.getGroup().equals("FDD-移动")) {
                            return 1;
                        } else {
                            return -1;
                        }
                    } else if (o1.info.getGroup().equals("FDD-电信")) {
                        if (o2.info.getGroup().equals("TDD-移动") || o2.info.getGroup().equals("FDD-移动") || o2.info.getGroup().equals("FDD-联通")) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }else if (o1.info.getGroup().equals("WCDMA")) {
                        if (o2.info.getGroup().equals("TDD-移动")
                                || o2.info.getGroup().equals("FDD-移动")
                                || o2.info.getGroup().equals("FDD-联通")
                                || o2.info.getGroup().equals("FDD-电信")) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }else if (o1.info.getGroup().equals("GSM")) {
                        if (o2.info.getGroup().equals("TDD-移动")
                                || o2.info.getGroup().equals("FDD-移动")
                                || o2.info.getGroup().equals("FDD-联通")
                                || o2.info.getGroup().equals("FDD-电信")
                                || o2.info.getGroup().equals("WCDMA")) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }


                }else if(o2.isHeader && !o1.isHeader){
                    if (o2.header.equals("TDD-移动")) {
                        return 1;
                    } else if (o2.header.equals("FDD-移动")) {
                        if (o1.info.getGroup().equals("TDD-移动")) {
                            return -1;
                        } else {
                            return 1;
                        }
                    } else if (o2.header.equals("FDD-联通")) {
                        if (o1.info.getGroup().equals("TDD-移动") || o1.info.getGroup().equals("FDD-移动")) {
                            return -1;
                        } else {
                            return 1;
                        }
                    } else if (o2.header.equals("FDD-电信")) {
                        if (o1.info.getGroup().equals("TDD-移动") || o1.info.getGroup().equals("FDD-移动")|| o1.info.getGroup().equals("FDD-联通")) {
                            return -1;
                        } else {
                            return 1;
                        }
                    } else if (o2.header.equals("WCDMA")) {
                        if (o1.info.getGroup().equals("TDD-移动")
                                || o1.info.getGroup().equals("FDD-移动")
                                || o1.info.getGroup().equals("FDD-联通")
                                || o1.info.getGroup().equals("FDD-电信")) {
                            return -1;
                        } else {
                            return 1;
                        }
                    }else if (o2.header.equals("GSM")) {
                        if (o1.info.getGroup().equals("TDD-移动")
                                || o1.info.getGroup().equals("FDD-移动")
                                || o1.info.getGroup().equals("FDD-联通")
                                || o1.info.getGroup().equals("FDD-电信")
                                || o1.info.getGroup().equals("WCDMA")) {
                            return -1;
                        } else {
                            return 1;
                        }
                    }
                }
                return 0;
            }

        });
        MMKVUtils.put(FKEY,new Gson().toJson(defaultItems));
        for(int i=0;i<defaultItems.size();i++) {
            Log.e(TAG, "sortList_end: " + new Gson().toJson(defaultItems.get(i)));
        }

    }



    private List<CustomGroupedItem> defaultItems;

    /**
     * 初始化控件
     */
    @Override
    protected void initViews() {
//        Log.e(TAG, "initViews: " +(List<CustomGroupedItem>) MMKVUtils.get("freqs",DemoDataProvider.getCustomGroupItems()) );

        if(StringUtils.isEmpty(MMKVUtils.getString(FKEY,null))){
            boolean f = MMKVUtils.put(FKEY,new Gson().toJson(DemoDataProvider.getCustomGroupItems()));
            Log.e(TAG, "initViews: " +  f );
        }

        defaultItems =  MMKVUtils.getObjectList(FKEY,CustomGroupedItem.class);
        Log.e(TAG, "initViews: " + defaultItems.size() );

//        for(int i=0;i<defaultItems.size();i++){
//            if(defaultItems.get(i).header!=null){
//                Log.e(TAG, "initViews: " + defaultItems.get(i).header);
//
//            }else if(defaultItems.get(i).info!=null ){
//                if(defaultItems.get(i).info.getGroup() !=null && defaultItems.get(i).info.getGroup().equals("移动")){
//                    continue;
//                }
//                String s = "";
//                if(defaultItems.get(i).info.getContent()!=null){
//                    s += " " + defaultItems.get(i).info.getContent();
//                }
//                if(defaultItems.get(i).info.getGroup()!=null){
//                    s += " " + defaultItems.get(i).info.getGroup();
//                }
//                if(defaultItems.get(i).info.getTitle()!=null){
//                    s += " " + defaultItems.get(i).info.getTitle();
//                }
//                Log.e(TAG, "initViews: " + s );
//            }
//        }

        sortList();
        binding.linkage.init(defaultItems, new CustomLinkagePrimaryAdapterConfig(this), new CustomLinkageSecondaryAdapterConfig(this));

    }

    @Override
    public void onPrimaryItemClick(LinkagePrimaryViewHolder holder, View view, String title) {
//        SnackbarUtils.Short(view, title).show();
    }

    @Override
    public void onSecondaryItemClick(LinkageSecondaryViewHolder holder, TextView view, BaseGroupedItem<CustomGroupedItem.ItemInfo> item) {
        if(item.info.getSelected()==0) {
            view.setBackgroundColor(Color.parseColor("#00BFFF"));
            item.info.setSelected(1);
        }else{
            view.setBackgroundColor(Color.parseColor("#ffffff"));
            item.info.setSelected(0);
        }

        Log.e(TAG, "onSecondaryItemClick: " + new Gson().toJson(item) );
        if(item.info!=null && item.info.getContent()!=null) {
            updateDefaultItems(item);
        }

        binding.linkage.getSecondaryAdapter().notifyDataSetChanged();
//        SnackbarUtils.Short(view, item.info.getTitle()).show();
    }

    void updateDefaultItems(BaseGroupedItem<CustomGroupedItem.ItemInfo> item){
        for(int i=0;i<defaultItems.size();i++){

            if(!defaultItems.get(i).isHeader && defaultItems.get(i).info.getContent().equals(item.info.getContent())){
                defaultItems.get(i).info = item.info;
                break;
            }
        }
        MMKVUtils.put(FKEY,new Gson().toJson(defaultItems));
    }

    @Override
    public void onSecondaryRemoveClick(LinkageSecondaryViewHolder holder, ButtonView view, BaseGroupedItem<CustomGroupedItem.ItemInfo> item) {
//        List<CustomGroupedItem> newList = new ArrayList<>();
//        newList.addAll(defaultItems);
        Log.e(TAG, "onSecondaryRemoveClick: " + new Gson().toJson(item) );
        if(item instanceof CustomGroupedItem){
            defaultItems.remove(item);
        }

        Log.e(TAG, "onSecondaryRemoveClick: " + defaultItems.size() );
//
//        for(int i = 0;i< newList.size();i++){
//            Log.e(TAG, "onSecondaryRemoveClick: " + new Gson().toJson(DemoDataProvider.getCustomGroupItems().get(i))  + "----" + item.info.getContent());
//
//            if( newList.get(i).info !=null
//                    && null != newList.get(i).info.getContent()
//                    && newList.get(i).info.getContent().equals(item.info.getContent())){
//
//            }
//        }

        binding.linkage.getSecondaryAdapter().initData(defaultItems);
        binding.linkage.getSecondaryAdapter().notifyDataSetChanged();
        MMKVUtils.put(FKEY,new Gson().toJson(defaultItems));
    }
}
